import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import Input from '@/components/Input'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { useDispatch } from 'react-redux'
import { Authorizations, sendCodes } from '@/store/action/user'
import { Toast } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useHistory, useLocation } from 'react-router-dom'

type formikValues = {
  mobile: string
  code: string
}
export default function Login() {
  const History = useHistory()

  // 登录之后看看是不是从需要登录的页面，由于没有token，重定向过来
  const location = useLocation<{ from: string }>()

  const formik = useFormik({
    initialValues: {
      mobile: '13811111111',
      code: '246810',
    } as formikValues,
    // 通过校验，点击登录
    onSubmit: async (values) => {
      await dispatch(Authorizations(values))
      Toast.show({ content: '登录成功', maskClassName: 'and_toast_win' })
      const path = location.state ? location.state.from : '/'
      
      History.push(path)
    },
    // Yup 表单校验
    validationSchema: Yup.object().shape({
      // 手机号校验
      mobile: Yup.string().required('不能为空').matches(/^1[3-9]\d{9}$/, '手机号格式错误'),
      // 验证码校验
      code: Yup.string().required('不能为空').matches(/^\d{6}$/, '验证码格式错误'),
    }),
  })


  const dispatch = useDispatch()
  // 验证码倒计时
  const [time, setTime] = useState(0)
  // 定义定时器
  const timeId = useRef(-1)
  // 点击发送验证码
  const handleSendCodes = async () => {
    if (time > 0) return
    if (formik.errors.mobile) return Toast.show({ content: formik.errors.mobile })
    await dispatch(sendCodes(formik.values.mobile))
    setTime(60)
    timeId.current = window.setInterval(() => {
      setTime((time) => {
        if (time === 1) clearInterval(timeId.current)
        return time - 1
      })
    }, 1000);
  }
  useEffect(() => {
    return () => {
      //组件卸载前触发的钩子
      clearInterval(timeId.current)
    }
  }, [])
  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className='content'>
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          {/* 手机号输入框 */}
          <Input
            placeholder='请输入手机号'
            autoFocus
            type='text'
            name='mobile'
            maxLength={11}
            errMsg={formik.touched.mobile ? formik.errors.mobile : ''}
            value={formik.values.mobile}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur} />
          {/* 短信验证码输入框 */}
          <Input
            placeholder='请输入验证码'
            type='text'
            name='code'
            maxLength={6}
            errMsg={formik.touched.code ? formik.errors.code : ''}
            extra={<span onClick={handleSendCodes}>{time === 0 ? '获取验证码' : `${time}s后在发送`}</span>}
            value={formik.values.code}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur} />

          {/* 登录按钮 */}
          <button type='submit' className='login-btn' disabled={!formik.isValid}>
            登录
          </button>
        </form>
      </div>
    </div >
  )
}
